<script setup lang="ts">
import type { VbenFormProps } from '@vben/common-ui';
import type { VxeGridProps } from '@vben/plugins/src/vxe-table/types';

import type { RowType } from './role.data';

import { Page, useVbenDrawer, useVbenModal } from '@vben/common-ui';

import { message, Modal } from 'ant-design-vue';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import {
  roleDelApi,
  roleDeleteBatchApi,
  roleQueryPageListApi,
} from '#/api/system/role';
import { queryDictOptionsApi, useDictionaries } from '#/utils';
import AuthorizationDrawer from '#/views/system/role/modules/AuthorizationDrawer.vue';

import RoleFormModal from './modules/RoleFormModal.vue';

const { translateValue } = useDictionaries(['status']);

const formOptions: VbenFormProps = {
  wrapperClass: 'grid-cols-1 md:grid-cols-2 lg:grid-cols-4',
  showCollapseButton: false,
  commonConfig: {
    colon: true,
    labelWidth: 80,
  },
  schema: [
    {
      component: 'Input',
      fieldName: 'roleName',
      label: '角色名称',
    },
    {
      component: 'Input',
      fieldName: 'roleCode',
      label: '角色编码',
    },
    {
      component: 'ApiSelect',
      componentProps: {
        afterFetch: (data) => {
          return data.map((item: any) => ({
            label: item.itemText,
            value: Number.parseInt(item.itemVal),
          }));
        },
        api: queryDictOptionsApi,
        params: {
          dictCode: 'status',
        },
        placeholder: '请选择状态',
        allowClear: true,
      },
      fieldName: 'status',
      label: '状态',
    },
  ],
};
const gridOptions: VxeGridProps<RowType> = {
  height: 'auto',
  toolbarConfig: {
    slots: {
      buttons: 'toolbar-buttons',
    },
  },
  columns: [
    { align: 'left', type: 'checkbox', width: 50 },
    { title: '序号', type: 'seq', width: 50 },
    { title: '角色名称', field: 'roleName', minWidth: 100 },
    { title: '角色编码', field: 'roleCode', minWidth: 100 },
    { title: '排序', field: 'sortRank', width: 50 },
    {
      title: '状态',
      cellRender: {
        name: 'CellDict',
        attrs: {
          dictCode: 'status',
          translateValue,
        },
      },
      field: 'status',
      minWidth: 80,
    },
    { title: '备注', field: 'remark', minWidth: 180 },
    {
      title: '创建时间',
      field: 'createData',
      formatter: 'formatDateTime',
      minWidth: 160,
    },
    {
      field: 'action',
      fixed: 'right',
      slots: { default: 'action' },
      title: '操作',
      minWidth: 160,
    },
  ],
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues) => {
        return await roleQueryPageListApi({
          pageNo: page.currentPage,
          pageSize: page.pageSize,
          ...formValues,
        });
      },
    },
  },
};
const [Grid, gridApi] = useVbenVxeGrid({ formOptions, gridOptions });

const [FromModal, formModalApi] = useVbenModal({
  connectedComponent: RoleFormModal,
  onOpenChange(isOpen: boolean) {
    if (!isOpen) {
      gridApi.query();
    }
  },
});
const [Drawer, drawerApi] = useVbenDrawer({
  connectedComponent: AuthorizationDrawer,
});

function openForm(id) {
  formModalApi.setData({
    id,
  });
  formModalApi.open();
}
function openAuth(row) {
  drawerApi.setData(row);
  drawerApi.open();
}
async function delRow(row) {
  const msg = await roleDelApi(row.id);
  message.success(msg);
  await gridApi.query();
}
async function delBatchRow() {
  const checkboxRecords = gridApi.grid.getCheckboxRecords();
  if (checkboxRecords.length === 0) {
    message.warn('至少选中一行');
  } else {
    const idArray = checkboxRecords.map((record) => record.id);
    const ids = idArray.join(',');
    Modal.confirm({
      title: '是否删除所选中行?',
      onOk() {
        roleDeleteBatchApi(ids).then(() => {
          message.success('删除成功');
          gridApi.query();
        });
      },
      class: 'test',
    });
  }
}
</script>

<template>
  <Page auto-content-height>
    <FromModal class="w-[50%]" />
    <Drawer class="w-[40%]" />
    <Grid>
      <template #toolbar-buttons>
        <a-button
          v-access:code="'sys:role:add'"
          type="primary"
          @click="openForm()"
        >
          新增
        </a-button>
      </template>
      <template #toolbar-tools>
        <a-button
          v-access:code="'sys:role:batchDel'"
          danger
          type="primary"
          @click="delBatchRow"
        >
          批量删除
        </a-button>
      </template>
      <template #action="{ row }">
        <a-button
          v-access:code="'sys:role:auth'"
          size="small"
          type="link"
          @click="openAuth(row)"
        >
          授权
        </a-button>
        <a-button
          v-access:code="'sys:role:edit'"
          size="small"
          type="link"
          @click="openForm(row.id)"
        >
          编辑
        </a-button>
        <a-popconfirm
          cancel-text="再想想"
          title="您确定要删除吗?"
          @confirm="delRow(row)"
        >
          <a-button
            v-access:code="'sys:role:del'"
            size="small"
            type="link"
            danger
          >
            删除
          </a-button>
        </a-popconfirm>
      </template>
    </Grid>
  </Page>
</template>
